import axios from 'axios';
let http = axios.create({
  timeout: 10000,
  baseURL: '/api',
});
http.interceptors.request.use(req => {
  let token = sessionStorage.getItem('token');
  token && (req.headers['header'] = `${token}`); //[]内的名字是后端接收解析token的字段名
  return req;
});
http.interceptors.response.use(
  resp => {
    resp.data.token && sessionStorage.setItem('token', resp.data.token);
    return resp;
  },
  error => {
    let _resp = error.response;
    switch (_resp.status) {
      case 401:
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('user');
        break;
      case 500:
        alert('服务器错误');
        break;
      default:
        break;
    }
    return Promise.reject(error.response.data);
  }
);

export default http;
